
import random
import time

from playwright.sync_api import Page, BrowserContext

from model.ProConfModel import ProConfModel
from tools.Ocr import get_position


def perform_slide(page, max_retries=3):
    """执行滑块验证，支持自动重试"""
    retry_count = 0
    while retry_count < max_retries:
        try:
            # 计算缺口位置
            try:
                bg_image_data = page.evaluate('''() => {  
                    const canvas = document.querySelector('canvas');  
                    return canvas.toDataURL('image/png').split(',')[1];  
                }''')
                slider_image_data = page.evaluate('''() => {  
                                    const canvas = document.querySelector('canvas.block');  
                                    return canvas.toDataURL('image/png').split(',')[1];  
                                }''')
                gap_x=get_position(slider_image_data,bg_image_data)
            except Exception as e:
                print(f"缺口检测失败，使用默认偏移量: {e}")
                gap_x = 50  # 备用值

            # 模拟拖动
            slider = page.query_selector(".slider")
            slider_bbox = slider.bounding_box()
            start_x = slider_bbox["x"] + slider_bbox["width"] / 2
            start_y = slider_bbox["y"] + slider_bbox["height"] / 2
            target_x = start_x + gap_x + 8

            page.mouse.move(start_x, start_y)

            page.mouse.down()
            steps = random.randint(15, 30)
            for i in range(steps):
                x = start_x + (target_x - start_x) * (i / steps)
                y = start_y + random.uniform(-2, 2)
                page.mouse.move(x, y)


            page.mouse.up()


            # 检查成功
            if page.query_selector(".prompt-info.success"):

                return True
            else:
                retry_count += 1
                print(f"验证失败，第 {retry_count} 次重试...")
                page.wait_for_timeout(1500)

        except Exception as e:
            print(f"滑动过程中出错: {e}")
            retry_count += 1

    return False

def login_with_slide(
    page: Page,
    pro_conf: ProConfModel ,
    max_slide_retries: int = 5
) -> bool:

    page.wait_for_timeout(1000)  # 简单延迟，确保响应已捕获
    """执行带滑块验证的登录，并返回登录接口的 JSON 数据"""
    page.goto(pro_conf.login_url, wait_until="networkidle", timeout=15000)
    #page.get_by_text("登录", exact=True).click()
    page.get_by_role("button", name="密码登录").click()
    page.get_by_role("textbox", name="手机号码").fill(pro_conf.login_name)
    page.get_by_role("textbox", name="密码").click()
    page.get_by_role("textbox", name="密码").fill(pro_conf.login_password)
    page.get_by_role("button", name="登录", exact=True).click()
    if not perform_slide(page, max_slide_retries):
        return False



    return True
